package com.aurora.oa.mycenter.view;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aurora.oa.Constants.AuroraConstants;
import com.aurora.oa.R;
import com.aurora.oa.activity.BaseActivity;
import com.aurora.oa.application.MyApplication;
import com.aurora.oa.bean.HttpResult;
import com.aurora.oa.customview.SelectPicPopupWindow;
import com.aurora.oa.listener.OnGetUserInfoListener;
import com.aurora.oa.listener.OnRequestHttpDataListener;
import com.aurora.oa.listener.OnRequestIsSuccessListener;
import com.aurora.oa.login.model.UserInfo;
import com.aurora.oa.message.bean.ResponseFileID;
import com.aurora.oa.model.RequestHttpModel;
import com.aurora.oa.model.RequestHttpModelImpl;
import com.aurora.oa.utils.ToastUtil;
import com.aurora.oa.utils.UriUtils;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.DatePicker;
import freemarker.template.utility.NormalizeNewlines;

/**
 * Created by Administrator on 2017/5/4 0004.
 */
public class MyInfoEditActivity extends BaseActivity {
    private static final int CHANGE_INFO = 1000;
    @Bind(R.id.sdv_head_img)
    SimpleDraweeView sdvHeadImg;
    @Bind(R.id.tv_right_arrow)
    TextView tvRightArrow;
    @Bind(R.id.rl_change_head_img)
    RelativeLayout rlChangeHeadImg;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.rl_change_name)
    RelativeLayout rlChangeName;
    @Bind(R.id.tv_sex)
    TextView tvSex;
    @Bind(R.id.rl_change_sex)
    RelativeLayout rlChangeSex;
    @Bind(R.id.tv_birthday)
    TextView tvBirthday;
    @Bind(R.id.rl_change_birthday)
    RelativeLayout rlChangeBirthday;
    @Bind(R.id.tv_duty)
    TextView tvDuty;
    @Bind(R.id.tv_enter_time)
    TextView tvEnterTime;
    @Bind(R.id.tv_city)
    TextView tvCity;
    @Bind(R.id.rl_change_city)
    RelativeLayout rlChangeCity;
    @Bind(R.id.tv_phone)
    TextView tvPhone;
    @Bind(R.id.rl_change_phone)
    RelativeLayout rlChangePhone;
    @Bind(R.id.tv_weixin)
    TextView tvWeixin;
    @Bind(R.id.rl_change_weixin)
    RelativeLayout rlChangeWeixin;
    @Bind(R.id.tv_email)
    TextView tvEmail;
    @Bind(R.id.rl_change_email)
    RelativeLayout rlChangeEmail;
    RequestHttpModel model = new RequestHttpModelImpl();
    private static final int TAKE_PHOTO = 1 ;
    private static final int PICK_PHOTO = 2;
    //自定义的弹出框类
    private SelectPicPopupWindow menuWindow;
    DatePicker datePicker;
    UserInfo myUserInfo;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initTitlebar(true, "修改个人信息", true);
        setMyContentView(R.layout.activity_change_info_main);
        initView();
        getData();
    }

    private void initView() {
        datePicker = new DatePicker(this);
        datePicker.setLabel("年","月","日");
        datePicker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                tvBirthday.setText(year+"-"+month+"-"+day);
                //上传生日
                String birthday = year+(month.length()==1?"0"+month:month)+(day.length()==1?"0"+day:day);
                Map<String,String> param = new HashMap<String, String>();
                param.put("birthday",birthday);
                model.doUpdateUserInfo(param, new OnRequestIsSuccessListener() {
                    @Override
                    public void onRequestSuccess(String info) {
                        getData();
                    }

                    @Override
                    public void onRequestFail(String message) {
                        ToastUtil.show(getApplicationContext(),message);
                    }
                });
            }
        });
    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener(){

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_take_photo:
                    Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(it, TAKE_PHOTO);
                    break;
                case R.id.btn_pick_photo:
                    Intent local = new Intent();
                    local.setType("image/*");
                    local.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(local, PICK_PHOTO);
                    break;
                default:
                    break;
            }
        }
    };
    private void getData() {
        model.getUserInfo(MyApplication.getInstance().getLoginUser().getId(), new OnGetUserInfoListener() {
            @Override
            public void onGetUserInfoSuccess(UserInfo userInfo) {
                myUserInfo = userInfo;
                refreshUI(userInfo);
            }

            @Override
            public void onGetUserInfoFail(String message) {
                ToastUtil.show(getApplicationContext(),message);
            }
        });
    }

    private void refreshUI(UserInfo userInfo) {
        tvBirthday.setText(userInfo.getBirthday());
        tvCity.setText(userInfo.getRegion());
        tvDuty.setText(userInfo.getPostname());
        tvEmail.setText(userInfo.getEmail());
        tvEnterTime.setText(userInfo.getEntrytime());
        tvName.setText(userInfo.getName());
        tvPhone.setText(userInfo.getMphone());
        tvSex.setText(userInfo.getSex());
        tvWeixin.setText(userInfo.getWeixin());
        sdvHeadImg.setImageURI(AuroraConstants.BASE_SERVER_URL+"/"+userInfo.getHeadimg());
    }

    @OnClick({R.id.rl_change_head_img, R.id.rl_change_name, R.id.rl_change_sex, R.id.rl_change_birthday, R.id.rl_change_city, R.id.rl_change_phone, R.id.rl_change_weixin, R.id.rl_change_email})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_change_head_img:
                menuWindow = new SelectPicPopupWindow(MyInfoEditActivity.this, itemsOnClick);
                //显示窗口
                menuWindow.showAtLocation(null, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置

                break;
            case R.id.rl_change_name:
                Intent cgNameIntent = new Intent(MyInfoEditActivity.this,ChangeUserInfoActivity.class);
                cgNameIntent.putExtra("title","姓名");
                cgNameIntent.putExtra("update_key",AuroraConstants.UserInfoKey.REAL_NAME);
                cgNameIntent.putExtra("value",myUserInfo.getRealname());
                startActivityForResult(cgNameIntent,CHANGE_INFO);
                break;
            case R.id.rl_change_sex:
                Intent cgSexIntent = new Intent(MyInfoEditActivity.this,ChangeUserInfoActivity.class);
                cgSexIntent.putExtra("title","性别");
                cgSexIntent.putExtra("update_key",AuroraConstants.UserInfoKey.SEX);
                cgSexIntent.putExtra("value",myUserInfo.getSex());
                startActivityForResult(cgSexIntent,CHANGE_INFO);
                break;
            case R.id.rl_change_birthday:
                datePicker.show();
                break;
            case R.id.rl_change_city:
                Intent cgRegionIntent = new Intent(MyInfoEditActivity.this,ChangeUserInfoActivity.class);
                cgRegionIntent.putExtra("title","地区");
                cgRegionIntent.putExtra("update_key",AuroraConstants.UserInfoKey.REGION);
                cgRegionIntent.putExtra("value",myUserInfo.getRegion());
                startActivityForResult(cgRegionIntent,CHANGE_INFO);
                break;
            case R.id.rl_change_phone:
                Intent cgPhoneIntent = new Intent(MyInfoEditActivity.this,ChangeUserInfoActivity.class);
                cgPhoneIntent.putExtra("title","电话");
                cgPhoneIntent.putExtra("update_key",AuroraConstants.UserInfoKey.MPHONE);
                cgPhoneIntent.putExtra("value",myUserInfo.getMphone());
                startActivityForResult(cgPhoneIntent,CHANGE_INFO);
                break;
            case R.id.rl_change_weixin:
                Intent cgWeiXinIntent = new Intent(MyInfoEditActivity.this,ChangeUserInfoActivity.class);
                cgWeiXinIntent.putExtra("title","微信");
                cgWeiXinIntent.putExtra("update_key",AuroraConstants.UserInfoKey.WEIXIN);
                cgWeiXinIntent.putExtra("value",myUserInfo.getWeixin());
                startActivityForResult(cgWeiXinIntent,CHANGE_INFO);
                break;
            case R.id.rl_change_email:
                Intent cgEmailIntent = new Intent(MyInfoEditActivity.this,ChangeUserInfoActivity.class);
                cgEmailIntent.putExtra("title","邮箱");
                cgEmailIntent.putExtra("update_key",AuroraConstants.UserInfoKey.EMAIL);
                cgEmailIntent.putExtra("value",myUserInfo.getEmail());
                startActivityForResult(cgEmailIntent,CHANGE_INFO);
                break;
        }
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch(requestCode) {
                case TAKE_PHOTO:
                    Bundle extras = data.getExtras();
                    Bitmap b = (Bitmap) extras.get("data");
                    String name = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
                    String fileNmae = Environment.getExternalStorageDirectory().toString()+ File.separator+"aurora/image/"+name+".jpg";
                    String srcPath = fileNmae;
                    File myCaptureFile =new File(fileNmae);
                    try {
                        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                            if(!myCaptureFile.getParentFile().exists()){
                                myCaptureFile.getParentFile().mkdirs();
                            }
                            BufferedOutputStream bos;
                            bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                            b.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                            bos.flush();
                            bos.close();
                            uploadHeadImg(myCaptureFile);
                        }else{

                            Toast toast= Toast.makeText(MyInfoEditActivity.this, "保存失败，SD卡无效", Toast.LENGTH_SHORT);
                            toast.show();
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                case PICK_PHOTO:
                    Uri uri = data.getData();
                    File file =new File(UriUtils.getRealFilePath(this,uri));
                    uploadHeadImg(file);
                    break;
                default:
                    break;
            };
        }
    }

    private void uploadHeadImg(File file) {
        model.postFile(AuroraConstants.POST_FILE_URL, file, new OnRequestHttpDataListener() {
            @Override
            public void onRequestDataSuccess(String body) {
                Gson gson = new Gson();
                ResponseFileID idData = gson.fromJson(body,ResponseFileID.class);
                if(idData!=null&&idData.isSuccess()) {
                    String attachId = idData.getMsg();
                    //附件上传完成,关联头像
                    model.doHeadUpload(attachId, new OnRequestHttpDataListener() {
                        @Override
                        public void onRequestDataSuccess(String body) {
                            Gson gson = new Gson();
                            HttpResult result = gson.fromJson(body,HttpResult.class);
                            if(result.success){
                                //重新获取界面数据
                                getData();
                            }
                        }

                        @Override
                        public void onRequestDataFail(String message) {
                            ToastUtil.show(getApplicationContext(),message);
                        }
                    });
                }else{
                    ToastUtil.show(getApplicationContext(),"头像上传失败");
                }

            }

            @Override
            public void onRequestDataFail(String message) {
                ToastUtil.show(getApplicationContext(),message);
            }
        });
    }
}
